﻿using FI.Core.Configuration;
using FI.Core.Properties;
using FI.Core.Utilities;
using System.Configuration;
using System.Linq;

namespace FI.Core.SettingSource.Configuration
{
    /// <summary>
    /// The <see cref="ConfigurationSection" /> for "FI.settingSource".
    /// </summary>
    [ConfigurationSectionName(Constants.ConfigurationSections.SettingSource)]
    public class SettingSourceSettings : ConfigurationSection
    {
        #region Constants
        private const string DefaultSettingSourcePropertyName = "defaultSettingSource";
        private const string SettingSourcesPropertyName = "settingSources";
        #endregion

        #region Properties
        /// <summary>
        /// Gets the default setting source.
        /// </summary>
        /// <value>
        /// The default setting source.
        /// </value>
        [ConfigurationProperty(DefaultSettingSourcePropertyName, IsRequired =true)]
        public string DefaultSettingSource
        {
            get { return (string)base[DefaultSettingSourcePropertyName]; }
        }

        /// <summary>
        /// Gets the setting sources.
        /// </summary>
        /// <value>
        /// The setting sources.
        /// </value>
        [ConfigurationProperty(SettingSourcesPropertyName, IsRequired = true)]
        public NameTypeConfigurationElementCollection<SettingSourceDataBase> SettingSources
        {
            get { return (NameTypeConfigurationElementCollection<SettingSourceDataBase>)base[SettingSourcesPropertyName]; }
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Gets the setting source.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        /// <exception cref="System.Configuration.ConfigurationErrorsException"></exception>
        public ISettingSource GetSettingSource(string name = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return this.SettingSources.GetConfigurationElement(this.DefaultSettingSource).CreateSettingSource();
            }

            if (this.SettingSources.Cast<SettingSourceDataBase>().Any(element => element.Name == name))
            {
                return this.SettingSources.GetConfigurationElement(name).CreateSettingSource();
            }

            throw new ConfigurationErrorsException(Resources.ExceptionSettingSourceNotExists.Format((object)name));
        }
        #endregion
    }
}
